package org.mms.controller;

import org.mms.pojo.dto.NewsDto;
import org.mms.pojo.entity.News;
import org.mms.pojo.request.NewsRequest;
import org.mms.pojo.util.ResponseMessage;
import org.mms.service.NewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/news")
public class NewsController {
    @Autowired
    private NewsService newsService;

    @GetMapping
    public ResponseMessage<List<NewsDto>> list() {
        return ResponseMessage.success(newsService.list()
                .stream()
                .map(News::convert)
                .toList());
    }

    @GetMapping("/{id}")
    public ResponseMessage<NewsDto> getById(@PathVariable Long id) {
        return ResponseMessage.success(newsService.getById(id)
                .convert());
    }

    @PostMapping
    public ResponseMessage<NewsDto> create(@RequestBody NewsRequest request) {
        return ResponseMessage.success(newsService.create(request.getTitle(), request.getContent(), request.getCoverUrl())
                .convert());
    }

    @PutMapping
    public ResponseMessage<NewsDto> update(@RequestBody NewsRequest request) {
        return ResponseMessage.success(
                newsService.update(request.getId(), request.getTitle(), request.getContent(), request.getCoverUrl())
                .convert());
    }

    @DeleteMapping("/{id}")
    public ResponseMessage<NewsDto> delete(@PathVariable Long id) {
        newsService.delete(id);
        return ResponseMessage.success(null);
    }

    @GetMapping("/search")
    public ResponseMessage<List<NewsDto>> search(@RequestParam("q") String query) {
        return ResponseMessage.success(newsService.search(query)
                .stream()
                .map(News::convert)
                .toList());
    }
}